{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      ">> Creating image 10000/10000\n",
      "生成完毕\n"
     ]
    }
   ],
   "source": [
    "# 验证码生成库\n",
    "from captcha.image import ImageCaptcha  # pip install captcha\n",
    "import numpy as np\n",
    "from PIL import Image\n",
    "import random\n",
    "import sys\n",
    " \n",
    "number = ['0','1','2','3','4','5','6','7','8','9']\n",
    "# alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\n",
    "# ALPHABET = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']\n",
    "\n",
    "def random_captcha_text(char_set=number, captcha_size=4):\n",
    "    # 验证码列表\n",
    "    captcha_text = []\n",
    "    for i in range(captcha_size):\n",
    "        #随机选择\n",
    "        c = random.choice(char_set)\n",
    "        #加入验证码列表\n",
    "        captcha_text.append(c)\n",
    "    return captcha_text\n",
    " \n",
    "# 生成字符对应的验证码\n",
    "def gen_captcha_text_and_image():\n",
    "    image = ImageCaptcha()\n",
    "    #获得随机生成的验证码\n",
    "    captcha_text = random_captcha_text()\n",
    "    #把验证码列表转为字符串\n",
    "    captcha_text = ''.join(captcha_text)\n",
    "    #生成验证码\n",
    "    captcha = image.generate(captcha_text)\n",
    "    image.write(captcha_text, 'captcha/images/' + captcha_text + '.jpg')  # 写到文件\n",
    "\n",
    "#数量少于10000，因为重名\n",
    "num = 10000\n",
    "if __name__ == '__main__':\n",
    "    for i in range(num):\n",
    "        gen_captcha_text_and_image()\n",
    "        sys.stdout.write('\\r>> Creating image %d/%d' % (i+1, num))\n",
    "        sys.stdout.flush()\n",
    "    sys.stdout.write('\\n')\n",
    "    sys.stdout.flush()\n",
    "                        \n",
    "    print(\"生成完毕\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [default]",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
